<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车数据加载测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        button { margin: 5px; padding: 10px; }
        pre { background: #f5f5f5; padding: 10px; overflow-x: auto; }
    </style>
</head>
<body>
    <h1>购物车数据加载测试</h1>
    
    <div class="test-section">
        <h3>1. 模拟Mike用户登录</h3>
        <button onclick="simulateMikeLogin()">模拟Mike登录</button>
        <div id="loginStatus"></div>
    </div>
    
    <div class="test-section">
        <h3>2. 测试购物车数据加载</h3>
        <button onclick="testCartLoad()">加载购物车数据</button>
        <div id="cartLoadStatus"></div>
    </div>
    
    <div class="test-section">
        <h3>3. 购物车数据</h3>
        <div id="cartData"></div>
    </div>
    
    <div class="test-section">
        <h3>4. 控制台日志</h3>
        <div id="consoleLog"></div>
    </div>

    <!-- 引入必要的脚本 -->
    <script src="js/api.js"></script>
    <script src="js/auth.js"></script>
    <script src="js/cart.js"></script>
    
    <script>
        // 重写console.log来显示在页面上
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        
        function addToConsole(message, type = 'info') {
            const logDiv = document.getElementById('consoleLog');
            const timestamp = new Date().toLocaleTimeString();
            logDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        console.log = function(...args) {
            originalLog.apply(console, args);
            addToConsole(args.join(' '), 'info');
        };
        
        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        console.error = function(...args) {
            originalError.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        // 模拟Mike用户登录
        function simulateMikeLogin() {
            const statusDiv = document.getElementById('loginStatus');
            try {
                // 模拟用户数据
                const userData = {
                    username: 'Mike',
                    user_id: 'USER001',
                    email: 'mike@example.com',
                    phone: '1234567890',
                    user_type: 'Customer',
                    token: 'test-token-mike'
                };
                
                // 保存到localStorage
                localStorage.setItem('currentUser', JSON.stringify(userData));
                localStorage.setItem('userData', JSON.stringify(userData));
                localStorage.setItem('authToken', userData.token);
                
                // 更新authManager状态
                if (window.authManager) {
                    window.authManager.currentUser = userData;
                    window.authManager.isLoggedIn = true;
                    window.authManager.userType = userData.user_type;
                    window.authManager.updateUI();
                }
                
                statusDiv.innerHTML = '<div class="success">✓ Mike用户登录成功</div>';
                console.log('Mike用户登录成功:', userData);
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">✗ 登录失败: ' + error.message + '</div>';
                console.error('登录失败:', error);
            }
        }
        
        // 测试购物车数据加载
        async function testCartLoad() {
            const statusDiv = document.getElementById('cartLoadStatus');
            const cartDataDiv = document.getElementById('cartData');
            
            try {
                if (!window.api) {
                    statusDiv.innerHTML = '<div class="error">✗ API模块未加载</div>';
                    return;
                }
                
                // 从后端获取购物车数据
                const result = await window.api.getCart();
                console.log('API返回结果:', result);
                
                if (result.success && result.data.items) {
                    statusDiv.innerHTML = '<div class="success">✓ 购物车数据加载成功</div>';
                    
                    // 显示购物车数据
                    cartDataDiv.innerHTML = `
                        <h4>购物车商品 (${result.data.items.length}件):</h4>
                        <pre>${JSON.stringify(result.data.items, null, 2)}</pre>
                        <p><strong>总价: ¥${result.data.total}</strong></p>
                    `;
                    
                    // 更新cartManager
                    if (window.cartManager) {
                        window.cartManager.items = result.data.items;
                        window.cartManager.selectedItems.clear();
                        window.cartManager.items.forEach(item => {
                            if (item.selected) {
                                window.cartManager.selectedItems.add(item.product_id);
                            }
                        });
                        window.cartManager.updateCartCount();
                        console.log('CartManager已更新');
                    }
                    
                } else {
                    statusDiv.innerHTML = '<div class="error">✗ 购物车数据为空或加载失败</div>';
                    cartDataDiv.innerHTML = '<p>购物车为空</p>';
                }
                
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">✗ 加载失败: ' + error.message + '</div>';
                console.error('加载购物车数据失败:', error);
            }
        }
        
        // 页面加载完成后运行测试
        window.addEventListener('load', () => {
            console.log('页面加载完成，开始测试...');
            
            // 延迟测试，确保所有模块都已加载
            setTimeout(() => {
                console.log('模块加载状态:');
                console.log('- API:', !!window.api);
                console.log('- AuthManager:', !!window.authManager);
                console.log('- CartManager:', !!window.cartManager);
            }, 500);
        });
    </script>
</body>
</html>
